<template>
  <div>
    <div style="display: flex;justify-content: space-between;">
      <el-upload
        action=""
        :auto-upload="false"
        :show-file-list="false"
        :on-change="handleFileUpload"
        accept=".xlsx,.xls"
      >
        <template #trigger>
          <el-button type="primary" style="margin-right: 10px">
            上传 Excel
          </el-button>
        </template>

        <el-button type="success" @click="download" plain>下载pdf</el-button>
      </el-upload>
      <a
        href="https://static.wxb.com.cn/frontEnd/files/excel/pdf-to-excel-model-1.xlsx"
        >模板下载</a
      >
    </div>

    <hr style="margin-bottom: 20px" />
    <!-- 渲染 Excel 生成的 HTML 表格 -->
    <div id="output" v-html="tableHtml" />
  </div>
</template>

<script setup>
import { ref } from "vue";
import * as ExcelJS from "exceljs";
import { downloadPDF } from "./tool.js";

const pdfName = ref("HB平安心有灵犀团意险");
const download = () => {
  downloadPDF(document.querySelector("#output"), pdfName.value);
};

const pdfModelValue = ref(1);
const sheetCustomStyles = {
  template1: {
    homePageStyle:
      "padding: 20px 28px 30px;background: linear-gradient( 180deg, #6AD5CE 0%, #E4F8F6 100%);",
    titleStyle:
      "font-size: 43px;color: #F9F9F9;text-align: center;font-weight: 600;margin-bottom: 41px;",
    sheet0: {
      specialFontStyle: ["color: #3AB1C9", "font-weight: bold"], // 特殊样式
      sheetStyle:
        "margin-bottom: 41px;padding:10px 10px;background: #fff;border-radius: 16px;",
      tableBoxStyle: "background: #E6F6FB;padding:10px 4px;position: relative;",
      tableSignStyle: `width: 284px;height: 44px;position: absolute;top: -27px;left:50%;transform: translateX(-50%);background: url(https://static.wxb.com.cn/frontEnd/images/common/ex-pdf-light.png) no-repeat;background-size: 100%,100%;`,
      single: {
        common: ["background: #E6F6FB"],
      },
      merges: {
        common: ["background: #E6F6FB"],
      },
    },
    sheet1: {
      sheetStyle:
        "padding:46px 10px 0;background: #fff;border-radius: 16px 16px 0 0;",
      tableBoxStyle: "position: relative;",
      tableSignStyle: `width: 284px;height: 44px;position: absolute;top: -63px;left:50%;transform: translateX(-50%);background: url(https://static.wxb.com.cn/frontEnd/images/common/ex-pdf-way.png) no-repeat;background-size: 100%,100%;`,
      single: {
        common: [
          "width: 100px",
          "padding: 0 10px",
          "border: 1px solid #29B1C9",
        ],
        row2: ["background: #29B1C9", "color: #fff", "border: 1px solid #fff"],
        row3: ["background: #29B1C9", "color: #fff", "border: 1px solid #fff"],
        col1: ["background: #E2F9FF", "color: #000"],
        col2: ["background: #E2F9FF", "color: #000"],
      },
      merges: {
        common: ["padding: 0 10px", "border: 1px solid #29B1C9"],
        row2: [
          "background: #29B1C9!important",
          "color: #fff!important",
          "border: 1px solid #fff",
        ],
        col1: ["background: #E2F9FF", "color: #000"],
        col2: ["background: #E2F9FF", "color: #000"],
        "row2-col1": ["border-left: 1px solid #29B1C9"],
      },
    },
    sheet2: {
      sheetStyle: "padding:20px 10px 0;background: #fff;",
      single: {
        common: ["width: 50px", "padding: 0 2px", "border: 1px solid #29B1C9"],
        col1: ["width: 100px", "background: #29B1C9", "color: #fff"],
      },
      merges: {
        common: ["width: 50px", "padding: 0 2px", "border: 1px solid #29B1C9"],
        col1: ["width: 100px", "background: #29B1C9", "color: #fff"],
        "row2-col1": ["border-bottom: 1px solid #fff"],
      },
    },
    sheet3: {
      sheetStyle: "padding:20px 10px 0;background: #fff;",
      single: {
        common: [],
      },
      merges: {
        common: [],
        row2: ["background: #fff", "color: #29B1C9"],
      },
    },
    sheet4: {
      sheetStyle: "padding:20px 10px 0;background: #fff;",
      single: {
        common: [],
      },
      merges: {
        common: [],
        row2: ["background: #fff", "color: #29B1C9"],
      },
    },
  },
};
const tableHtml = ref(""); // 存储 HTML 表格内容
const themeColors = {
  0: "#FFFFFF", // 白色 √
  1: "#000000", // 黑色 √
  2: "#C9CDD1", // 灰色 √
  3: "#4874CB", // 蓝色 √
  4: "#D9E1F4", // 浅蓝 √
  5: "#F9CBAA", // 橙色 √
  6: "#F2BA02", // 浅橙 √
  7: "#00FF00", // 浅绿 √
  8: "#30C0B4", // 青色 √
  9: "#E54C5E", // 红色 √
  10: "#FFC7CE", // 浅红
  11: "#7030A0", // 紫色
};
// 获取单元格颜色
const getCellColor = (cell) => {
  if (cell.fill && cell.fill.fgColor) {
    if (cell.fill.fgColor.argb) {
      return `#${cell.fill.fgColor.argb.substring(2)}`; // ARGB 转 RGB
    }
    if (cell.fill.fgColor.theme !== undefined) {
      return themeColors[cell.fill.fgColor.theme] || "#FFFFFF"; // 主题色转换
    }
  }

  return ""; // 无颜色
};
// 获取单元格字体颜色
const getCellFontColor = (cell) => {
  if (cell.font && cell.font.color && cell.font.color.argb) {
    return `#${cell.font.color.argb.substring(2)}`; // ARGB 转 RGB
  }
  if (cell.font && cell.font.color && cell.font.color.theme) {
    return themeColors[cell.font.color.theme] || "#000"; // 主题色转换
  }

  return "#000"; // 默认黑色
};

//处理特殊样式
const handleSpecialStyle = (
  cell,
  currentSheetIndex,
  styles,
  styleDataPrefix
) => {
  if (currentSheetIndex === 0 && getCellFontColor(cell) === "#FF0000") {
    styles.push(...styleDataPrefix?.specialFontStyle);
  }
};
const handleStyles = (cell, options) => {
  // console.log('col',col)
  // console.log('row',row)
  const currentSheetIndex = worksheetIds.indexOf(options.sheetId);
  let styles = [];

  // 读取字体颜色
  styles.push(`color: ${getCellFontColor(cell)}`);
  // 读取背景色
  styles.push(`background-color: ${getCellColor(cell)}`);

  // 加粗
  if (cell.font && cell.font.bold) {
    styles.push("font-weight: bold");
  }

  // 文字对齐
  if (cell.alignment) {
    if (cell.alignment.horizontal) {
      styles.push(`text-align: ${cell.alignment.horizontal}`);
    }
    if (cell.alignment.vertical) {
      styles.push(`vertical-align: ${cell.alignment.vertical}`);
    }
  }

  const styleDataPrefix =
    sheetCustomStyles[`template${pdfModelValue.value}`][
      `sheet${currentSheetIndex}`
    ];
  if (options.mergeSign === "merge") {
    styles = styles.concat(styleDataPrefix?.merges?.common);

    styleDataPrefix["merges"][`row${cell.row}`] &&
      styles.push(...styleDataPrefix["merges"][`row${cell.row}`]);
    styleDataPrefix["merges"][`col${cell.col}`] &&
      styles.push(...styleDataPrefix["merges"][`col${cell.col}`]);
    styleDataPrefix["merges"][`row${cell.row}-col${cell.col}`] &&
      styles.push(
        ...styleDataPrefix["merges"][`row${cell.row}-col${cell.col}`]
      );
  } else {
    styles = styles.concat(styleDataPrefix?.single?.common);

    styleDataPrefix["single"][`row${cell.row}`] &&
      styles.push(...styleDataPrefix["single"][`row${cell.row}`]);
    styleDataPrefix["single"][`col${cell.col}`] &&
      styles.push(...styleDataPrefix["single"][`col${cell.col}`]);
    styleDataPrefix["single"][`row${cell.row}-col${cell.col}`] &&
      styles.push(
        ...styleDataPrefix["single"][`row${cell.row}-col${cell.col}`]
      );
  }

  //处理特殊样式
  handleSpecialStyle(cell, currentSheetIndex, styles, styleDataPrefix);

  return styles.join("; ");
};

// 处理合并单元格内容
const handleValue = (value) => {
  if (value && typeof value === "object" && value.richText) {
    console.log("value.richText", value.richText);
    const valueArr = value.richText.reduce((acc, curr) => {
      let colorValue = "";
      if (curr.font && curr.font.color && curr.font.color.argb) {
        colorValue = `#${curr.font.color.argb.substring(2)}`;
      } else {
        colorValue = `#000`;
      }

      const newData = curr.text
        .split(/\r/)
        .map((item) => `<p style="color:${colorValue}">${item}</p>`);
      return acc.concat(newData);
    }, []);

    return valueArr.join("").replace(/\n/g, "<br />");
  }

  return value ? value : "";
};
// 处理常规单元格内容
const handleValueSimple = (value) => {
  if (value && typeof value === "object" && value.richText) {
    const valueStr = value.richText.reduce((acc, curr) => {
      let colorValue = "";
      if (curr.font && curr.font.color && curr.font.color.theme) {
        colorValue = getCellFontColor(curr) || `#000`;
      }
      if (curr.font && curr.font.color && curr.font.color.argb) {
        colorValue = `#${curr.font.color.argb.substring(2)}`;
      } else {
        colorValue = `#000`;
      }

      return acc + `<span style="color:${colorValue}">${curr.text}</span>`;
    }, "");

    return valueStr;
  }

  return value ? value : "";
};

// 处理上传的 Excel 文件
const handleFileUpload = async (file) => {
  const excelData = await readExcel(file.raw);
  tableHtml.value = excelData; // 更新 HTML 表格内容
};

let worksheetIds = [];
// 读取 Excel 并转换成 HTML
const readExcel = async (file) => {
  const workbook = new ExcelJS.Workbook();
  const arrayBuffer = await file.arrayBuffer();
  const { worksheets } = await workbook.xlsx.load(arrayBuffer);
  // console.log('worksheets',worksheets)
  worksheetIds = worksheets.map((v) => v.id);
  // const worksheet =  workbook.getWorksheet(1); // 读取第一个工作表
  let allHtml = "";
  allHtml += `<div style="${
    sheetCustomStyles["template" + [pdfModelValue.value]]["homePageStyle"]
  }">`;
  allHtml += `<div style="${
    sheetCustomStyles["template" + [pdfModelValue.value]]["titleStyle"]
  }">${pdfName.value}</div>`;
  workbook.eachSheet(function (worksheet, sheetId) {
    // console.log('worksheet',worksheet)
    // console.log('sheetId',sheetId)
    // 处理合并单元格
    const merges = worksheet?.model?.merges || [];
    // console.log('merges',merges)
    const currentSheetIndex = worksheetIds.indexOf(sheetId);

    let html = `<div class="sheet" style="${
      sheetCustomStyles["template" + [pdfModelValue.value]][
        "sheet" + currentSheetIndex
      ]["sheetStyle"]
    }">`;
    html += `<div class="table-box" style="${
      sheetCustomStyles["template" + [pdfModelValue.value]][
        "sheet" + currentSheetIndex
      ]["tableBoxStyle"]
    }">`;
    html += `<div class="table-sign" style="${
      sheetCustomStyles["template" + [pdfModelValue.value]][
        "sheet" + currentSheetIndex
      ]["tableSignStyle"]
    }"></div>`;
    html += '<table style="border-collapse: collapse;">';

    worksheet.eachRow({ includeEmpty: true },(row, rowIndex) => {
      html += "<tr>";

      row.eachCell({ includeEmpty: true },(cell, colIndex) => {
        // console.log(cell, 'cellcellcell')
        // console.log(cell.row,cell.col)
        let cellValue = cell.value || "";
        // console.log(cellValue, 'cellValuecellValue111')

        // 处理合并单元格
        let rowspan = 1,
          colspan = 1;
        let isMerged = false;

        for (let merge of merges) {
          // console.log(merges, 'mergesmergesmerges')
          // console.log(cellValue, 'cellValuecellValue------mergemergemerge')
          const [start, end] = merge.split(":");
          const startCell = worksheet.getCell(start);
          const endCell = worksheet.getCell(end);
          const startRow = startCell.row,
            startCol = startCell.col;
          const endRow = endCell.row,
            endCol = endCell.col;

          if (startRow === rowIndex && startCol === colIndex) {
            rowspan = endRow - startRow + 1;
            colspan = endCol - startCol + 1;
            isMerged = true;

            let styles = handleStyles(cell, { mergeSign: "merge", sheetId });
            html += `<td rowspan="${rowspan}" colspan="${colspan}" style="${styles}">${handleValue(
              startCell.value
            )}</td>`;
            break;
          }
          if (
            rowIndex >= startRow &&
            rowIndex <= endRow &&
            colIndex >= startCol &&
            colIndex <= endCol
          ) {
            isMerged = true;
            break;
          }
        }

        if (!isMerged) {
          let styles = handleStyles(cell, { mergeSign: "noMerge", sheetId });

          // console.log(cellValue, 'cellValuecellValue222')
          // 生成 HTML 单元格
          html += `<td ${rowspan > 1 ? `rowspan="${rowspan}"` : ""} ${
            colspan > 1 ? `colspan="${colspan}"` : ""
          } style="${styles}">${handleValueSimple(cellValue)}</td>`;
        }
      });

      html += "</tr>";
    });

    html += "</table>";
    html += "</div>"; //sheet的闭合标签
    html += "</div>"; //shee的闭合标签
    allHtml += html;
  });

  allHtml += "</div>";
  return allHtml;
};
</script>

<style scoped></style>
